package zencstudio.sgrealtor.view.phone;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import zencstudio.sgrealtor.R;
import zencstudio.sgrealtor.model.LoanCalculateRequest;
import zencstudio.sgrealtor.model.LoanTermData;
import zencstudio.sgrealtor.service.IWireFrameService;
import zencstudio.sgrealtor.service.WireFrameServiceFactory;
import zencstudio.sgrealtor.utils.Const;
import zencstudio.sgrealtor.utils.DeviceInfo;
import zencstudio.sgrealtor.utils.WFErrorCode;
import zencstudio.sgrealtor.utils.WFUtils;
import zencstudio.sgrealtor.view.common.BaseCalculationActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class LoanCalculator extends BaseCalculationActivity implements View.OnClickListener{
		private TableLayout tableResult;
		private EditText txtTypeInterest;
		private TextView loanResult;
		private List<LoanTermData> listTerm = new ArrayList<LoanTermData>();
		private Button btnChart;
		List<Button>btnTermOfLoans = new ArrayList<Button>();
		private String termOfLoan = "";
		private EditText txtAmount;
		private int MAX_TERM_OF_YEARS = 8;
		
		public void onCreate(Bundle saveInstance){
			super.onCreate(saveInstance);
			if(!WFUtils.checkInternetConnection(this)){
				showNetworkErrorDlg();
				return;
			}
			initTermOfLoanButtons();
			loadData();
		}
		@Override
		protected void initUI() {
			setContentView(R.layout.loancalculator);
			
			        
		}
		private double PMT(double i, double n, double p){	
			return i*p/(1-Math.pow((1 + i),-n));
		}
		private void buttonControl(String loanLength){
			String interestData = txtTypeInterest.getText().toString();
			String amount = txtAmount.getText().toString();
			if (interestData.isEmpty()){
				interestData="1.50";
			}
			termOfLoan = loanLength;
			double i_ = Double.parseDouble(interestData);
			double n_ = Double.parseDouble(loanLength);
			double p_ = Double.parseDouble(amount);
			double result = PMT(i_/1200,12*n_,p_);
			DecimalFormat df=new DecimalFormat("0.00");
			df.setRoundingMode(RoundingMode.UP);
			loanResult.setText("$ "+df.format(result));
			
		}
		private void setBackground(int selectedIdex){
			tableResult.setVisibility(View.VISIBLE);
			for(int i=0;i<btnTermOfLoans.size();i++){
				if(i==0){
					btnTermOfLoans.get(i).setBackgroundResource(R.drawable.button_calculator_left_radius);
				}else if(i==btnTermOfLoans.size()-1){
					btnTermOfLoans.get(i).setBackgroundResource(R.drawable.button_calculator_radius_right);
				}
				else{
					btnTermOfLoans.get(i).setBackgroundResource(R.drawable.button_calculator_center);
				}
			}
			if(selectedIdex==0){
				btnTermOfLoans.get(selectedIdex).setBackgroundResource(R.drawable.button_bg_calculator_left_selected);
			}else if(selectedIdex==btnTermOfLoans.size()-1){
				btnTermOfLoans.get(selectedIdex).setBackgroundResource(R.drawable.button_bg_calculator_right_selected);
			}
			else{
				btnTermOfLoans.get(selectedIdex).setBackgroundResource(R.drawable.button_bg_calculator_center_selected);
			}
		}
		private void loadData(){
			tableResult = (TableLayout) findViewById(R.id.table_result);
			tableResult.setVisibility(View.INVISIBLE);
			loanResult = (TextView) findViewById(R.id.calculator_result);
			
			
			txtTypeInterest = (EditText) findViewById(R.id.txtTypeInterest);
		
			Resources resources = getResources();
			String[] listTermData = resources.getStringArray(R.array.term_loan_array);
			for (int i=0;i<listTermData.length;i++){
				listTerm.add(new LoanTermData(listTermData[i]));
			}
	        
	        TextView title = (TextView) findViewById(R.id.txtTitle);
			title.setText(getString(R.string.loan_calculator));
			txtAmount = (EditText)findViewById(R.id.txtAmount);
	        //btCalculator = (Button) findViewById(R.id.btCalculator);
	        btnChart = (Button) findViewById(R.id.btnChart);
	        btnChart.setOnClickListener(new View.OnClickListener() {				
				@Override
				public void onClick(View v) {
					if(!validateData())
						return;
					showProgressDlg();
					Thread thread = new Thread(new Runnable() {
						
						@Override
						public void run() {
							Message msg = handler.obtainMessage();
							IWireFrameService service = WireFrameServiceFactory.getInstance().getService();
							
							int screenWidth = DeviceInfo.ScreenHeight;
							
							String amount = txtAmount.getText().toString();
							String interestData = txtTypeInterest.getText().toString();
							LoanCalculateRequest request = new LoanCalculateRequest();
							
							request.amount = amount;
							request.rate = interestData;
							request.term = termOfLoan;
							
							if (interestData.isEmpty()){
								request.rate = "1.50";
							}
							else {
								request.rate =interestData;
							}
							request.screenWidth = screenWidth;
							try {
								Bitmap bm = service.calculate(request);
								msg.obj = bm;
								handler.sendMessage(msg);
							} catch (Exception e) {
								msg.arg1 = WFErrorCode.NETWORK_ERROR.getValue();
								e.printStackTrace();
							}
						}
					});
					thread.start();
				}
			});
	        
		}
		@SuppressLint("HandlerLeak")
		private Handler handler = new Handler(){
			public void handleMessage (Message msg){
				dismissProgressDlg();
				if(msg.arg1==WFErrorCode.NETWORK_ERROR.getValue()){
					showNetworkErrorDlg();
					return;
				}
				if(msg.obj!=null){
					Intent intent = new Intent(LoanCalculator.this,ChartActivity.class);
					if(Const.CATCH_CHART!=null)
					{
						Const.CATCH_CHART.recycle();
						Const.CATCH_CHART = null;
					}
					Const.CATCH_CHART = (Bitmap) msg.obj;
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
					startActivity(intent);
				}
			}
		};
		private boolean validateData(){
			Animation animFadein = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.sequence_button);
			if(txtAmount.getText().toString().isEmpty()){
				Toast.makeText(this, R.string.msg_field_not_empty, Toast.LENGTH_SHORT).show();
				txtAmount.startAnimation(animFadein);
				return false;
			}
			return true;
		}
		private void initTermOfLoanButtons(){
			LayoutInflater inflater = 
		              (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			TableLayout tbLayout = (TableLayout) findViewById(R.id.termOfLoan);
			TableRow tbRow = (TableRow) tbLayout.getChildAt(0);
			View view = null;
			for(int i=0;i<MAX_TERM_OF_YEARS;i++){
				if(i==0)
					view = inflater.inflate(R.layout.calculator_button_item_left, null,false);
				else if(i==MAX_TERM_OF_YEARS-1)
					view = inflater.inflate(R.layout.calculator_button_item_right, null,false);
				else
					view = inflater.inflate(R.layout.calculator_button_item, null,false);
				Button btn = (Button) view.findViewById(R.id.btnTermOfLoan);
				btn.setText(5*(i+1)+"");
				btn.setTag(i);
				btn.setOnClickListener(this);
				tbRow.addView(view);			
				btnTermOfLoans.add(btn);
			}
		}
		@Override
		public void onClick(View v) {
			if(!validateData())
				return;
			
			Button btn = (Button) v;
			setBackground((Integer)btn.getTag());
			buttonControl(btn.getText().toString());
		}
}
